package com.ft.oa.service.clueprojectService.Impl;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ft.oa.domain.clueproject.ClueProject;
import com.ft.oa.domain.clueproject.ClueProjectOtherPeople;
import com.ft.oa.domain.clueproject.ThreadContact;
import com.ft.oa.domain.dto.ApiResult;
import com.ft.oa.domain.dto.knowledgeBase.AttachmentDto;
import com.ft.oa.domain.dto.sys.SecurityUser;
import com.ft.oa.enums.DirectoryTypeEnum;
import com.ft.oa.mapper.clueprojectMapper.ClueProjectMapper;
import com.ft.oa.mapper.clueprojectMapper.ClueProjectOtherPeopleMapper;
import com.ft.oa.security.constant.SecurityConstant;
import com.ft.oa.service.clueprojectService.IclueprojectService;
import com.ft.oa.service.knowledgeBase.DirectoryService;
import com.ft.oa.utils.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

@Service
public class ClueprojectImpl implements IclueprojectService {

    @Resource
    private ClueProjectMapper clueProjectMapper;
    // 客户联络人
    @Resource
    private ClueProjectOtherPeopleMapper clueProjectOtherPeopleMapper;

    @Resource
    private DirectoryService directoryService;

    @Override
    public ThreadContact getprojectthread(Long threadId) {
        QueryWrapper<ClueProject> ClueProjectwrapper = new QueryWrapper<>();
        ClueProjectwrapper.eq("id",threadId);
        ClueProjectwrapper.eq("delldust","0");
        ThreadContact threadContact = new ThreadContact();
        ClueProject clueProject = clueProjectMapper.selectOne(ClueProjectwrapper);
        String achment = clueProject.getAchment();
        clueProject.setAchment("");
        clueProject.setAttachments(JSONObject.parseArray(achment, AttachmentDto.class));
        threadContact.setClueProject(clueProject);
        QueryWrapper<ClueProjectOtherPeople> ClueProjectOtherPeoplewrapper = new QueryWrapper<>();
        ClueProjectOtherPeoplewrapper.eq("clue_project_id",threadId);
        List<ClueProjectOtherPeople> clueProjectOtherPeople = clueProjectOtherPeopleMapper.selectList(ClueProjectOtherPeoplewrapper);
        threadContact.setListClueproject(clueProjectOtherPeople);
        return threadContact;
    }

    @Override
    public int updateprojectthread(ClueProject clueProject) {
        QueryWrapper<ClueProject> wrapper = new QueryWrapper<>();
        wrapper.eq("id",clueProject.getId());
        return clueProjectMapper.update(clueProject, wrapper);
    }
    @Override
    @Transactional
    public ApiResult addprojectthread(ThreadContact threadContact) {
        ClueProject clueProject = threadContact.getClueProject();
        String projectNumber = clueProject.getProjectNumber();
        QueryWrapper<ClueProject> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(ClueProject::getProjectNumber,projectNumber);
        Integer integer = clueProjectMapper.selectCount(wrapper);
        if(integer!=0){
            return ApiResult.builder().code(2000).msg("新增失败").data("项目编号以重复").build();
        }else{
            // 获取当前用户信息
            SecurityUser currentUser = SecurityUtils.getCurrentUser();
            // 获取当前用户名称用作展示售前项目管理
            Long creator = currentUser.getId();
            clueProject.setCreator(creator);
            List<AttachmentDto> attachments = clueProject.getAttachments();
            if(attachments != null && attachments.size() > 0){
                String json = JSONArray.toJSONString(attachments);
                clueProject.setAchment(json);
            }else{
                clueProject.setAchment(null);
            }
            clueProjectMapper.insert(clueProject);
            directoryService.saveProAttachment(attachments, DirectoryTypeEnum.PRO_FD_CLUE.getCode(),String.valueOf(clueProject.getId()),null,projectNumber);
            Long id = clueProject.getId();
            List<ClueProjectOtherPeople> listClueproject = threadContact.getListClueproject();
            for (ClueProjectOtherPeople OtherPeopleList:listClueproject) {
                OtherPeopleList.setClueProjectId(id);
                clueProjectOtherPeopleMapper.insert(OtherPeopleList);
            }
            // 页面传过来的线索主表信息
            return ApiResult.simpleSuccess();
        }
    }

    @Override
    public int updateclue(ThreadContact threadContact) {
        ClueProject clueProject = threadContact.getClueProject();
        QueryWrapper<ClueProject> wrapper = new QueryWrapper();
        Long id = clueProject.getId();
        List<AttachmentDto> attachments = clueProject.getAttachments();
        if(attachments != null && attachments.size() > 0){
            String json = JSONArray.toJSONString(attachments);
            clueProject.setAchment(json);
        }else{
            clueProject.setAchment(null);
        }
        wrapper.eq("id",id);
        int num = clueProjectMapper.update(clueProject, wrapper);

        QueryWrapper<ClueProjectOtherPeople> otherwrapper = new QueryWrapper();
        otherwrapper.eq("clue_project_id",id);
        clueProjectOtherPeopleMapper.delete(otherwrapper);

        List<ClueProjectOtherPeople> listClueproject = threadContact.getListClueproject();
        listClueproject.forEach(OtherPeopleList ->{
            OtherPeopleList.setClueProjectId(id);
            clueProjectOtherPeopleMapper.insert(OtherPeopleList);
        });

        return num;
    }

    @Override
    public int dellteclue(Long threadId) {
        QueryWrapper<ClueProject> wrapper = new QueryWrapper();
        wrapper.eq("id",threadId);
        ClueProject clueProject = new ClueProject();
        clueProject.setDelldust("1");
        return clueProjectMapper.update(clueProject,wrapper);
    }

    @Override
    public HashMap<String, Object> vallthread(String clientname, String importantLevel, String xsstatus , int page, int size) {
        QueryWrapper<ClueProject> wrapper = new QueryWrapper();
        wrapper.eq("delldust","0");
        // 获取当前用户信息
        SecurityUser currentUser = SecurityUtils.getCurrentUser();
        boolean roledesc= false;
        // 获取当前用户名称用作展示售前项目管理
        Long creator = currentUser.getId();
        //获取用户权限 如果是admin 则是管理员 可以查看到全部
        Set<String> roles = currentUser.getRoles();
        for (String role:roles) {
            if(role.equals(SecurityConstant.SUPER_ROLE)){
                roledesc=true;
            }
        }
        if(!StringUtils.isEmpty(clientname)){
            wrapper.like("xsname",clientname);
        }
        if(!StringUtils.isEmpty(importantLevel)){
            wrapper.eq("important_level",importantLevel);
        }
        if(!StringUtils.isEmpty(xsstatus)){
            wrapper.eq("xsstatus",xsstatus);
        }
        if(roledesc){

        }else{
            wrapper.eq("creator",creator);
        }
        Page<ClueProject> pagethreadtion = new Page<>(page, size);
        Page<ClueProject> threadPage = clueProjectMapper.selectPage(pagethreadtion, wrapper.orderByDesc("create_time"));
        //获取总记录数
        long total = threadPage.getTotal();
        List<ClueProject> records = threadPage.getRecords();
        records.forEach(e -> {
            if (e.getAchment() != null) {
                e.setAttachments(JSONObject.parseArray(e.getAchment(), AttachmentDto.class));
            }
        });
        HashMap<String,Object> threadMap = new HashMap<>();
        threadMap.put("total",total);
        threadMap.put("thread",records);
        return threadMap;
    }

    @Override
    public List getclueAll() {
        LambdaQueryWrapper<ClueProject> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ClueProject::getDelldust,"0");
        return clueProjectMapper.selectList(wrapper);
    }
}
